import { createId } from '@/utils/tools-mind'
const state = {
  rootCard: {
    id: createId(),
    type: 'main-card',
    name: '',
    code: '',
    spec: '',
    model: '',
    parent: [],
    positon: ''
  },
  nodeCards: [],
  codeType: '1',
  // 数据源
  target_schema: '',
  target_customer: '',
  target_ds: ''
}

const mutations = {
  addNodeCards(state, payload) {
    if (Array.isArray(payload)) {
      state.nodeCards.push(...payload)
      // 去重
      let map = new Map()
      for (let item of state.nodeCards) {
        if (!map.has(item.id)) {
          map.set(item.id, item)
        }
      }
      state.nodeCards = [...map.values()]
    } else {
      state.nodeCards.push(payload)
    }
  },
  cleanNodeCards(state, payload) {
    state.nodeCards = []
  },
  cleanSonNodeCards(state, parentId) {
    state.nodeCards = state.nodeCards.filter((v) => v.parent[v.parent.length - 1] !== parentId)
  },
  changeNodeCard(state, payload) {
    payload.parent.forEach((p) => {
      state.nodeCards.children.find((n) => n.id === p).children.push(payload)
    })
  },
  setNodesActive(state, { payload, containerBg }) {
    const arr = [...payload.parent, payload.id]
    state.nodeCards.forEach((v) => {
      v.active = false
      v.containerBg = ''
      if (v.id === payload.id) {
        v.containerBg = containerBg
      }
      v.active = arr.includes(v.id)
      return v
    })
  },
  SET_CODE_TYPE(state, codeType) {
    state.codeType = codeType
  },
  SET_TARGET_SCHEMA(state, target_schema) {
    state.target_schema = target_schema
  },
  SET_TARGET_CUSTOMER(state, target_customer) {
    state.target_customer = target_customer
  },
  SET_TARGET_DS(state, target_ds) {
    state.target_ds = target_ds
  }
}

const actions = {
  saveDataOrigin({ commit }, { target_schema, target_customer, target_ds }) {
    commit('SET_TARGET_SCHEMA', target_schema)
    commit('SET_TARGET_CUSTOMER', target_customer)
    commit('SET_TARGET_DS', target_ds)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
